package com.miao.teacher.ui;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

import com.google.gson.Gson;
import com.miao.teacher.adapter.MyRevisePageAdapter;
import com.miao.teacher.app.ApplicationMain;
import com.miao.teacher.controls.LocalRevise;
import com.miao.teacher.models.ReviseInfo;
import com.espeaker.sdk.Constants;
import com.espeaker.sdk.api.ReviseApi;
import com.espeaker.sdk.model.ReviseJson;
import com.espeaker.sdk.utils.JsonUtils;
import com.miao.teacher.presenters.OnMenuClickedListener;
import com.miao.teacher.presenters.OnMenuSelectListener;
import com.miao.teacher.presenters.OnReviseListener;
import com.miao.teacher.utils.ConvertUtils;
import com.miao.teacher.utils.DBUtil;
import com.miao.teacher.utils.Utils;
import com.miao.teacher.widget.BTViewPager;
import com.miao.teacher.widget.WaitingDialog;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class ReviseActivity extends BaseFragmentActivity implements
		OnMenuClickedListener, OnMenuSelectListener, OnReviseListener {

	private static final String XIAOFEI_ID = "extra.xiaofei_id";

	private BTViewPager mPagerVp;
	private MyRevisePageAdapter mPageAdapter = null;

	private ImageView image;
	private TextView view1, view2, view3;
	private int currIndex;// 当前页卡编号
	private int bmpW;// 横线图片宽度

	private ReviseJson mCurReviseJson;
	private ReviseInfo rInfo;

	private ReviseApi api = new ReviseApi();

	private AlertDialog alertDialog = null;

	private String Question = "";

	private ProgressDialog pd;

	private int IsSubmit = 0;

	// private WaitingDialog waitDialog;

	/*
	 * 创建实例
	 */
	public static void createInstance(Context context, int xiaofei_id) {
		Intent intent = new Intent();
		intent.setClass(context, ReviseActivity.class);
		intent.putExtra(XIAOFEI_ID, xiaofei_id);
		context.startActivity(intent);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_revise_rate);
		findViewById(R.id.lly_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				DoSaveAudio();
				finish();
			}
		});
		if (getIntent().hasExtra(XIAOFEI_ID)) {
			int xiaofei_id = getIntent().getIntExtra(XIAOFEI_ID, 0);
			rInfo = LocalRevise
					.getByXiaoFeiId(new DBUtil(this).sld, xiaofei_id);
			if (rInfo != null) {
				Gson gson = new Gson();
				mCurReviseJson = gson.fromJson(rInfo.json, ReviseJson.class);
				if (mCurReviseJson.mFiles == null) {
					mCurReviseJson.mFiles = new ArrayList<String>();
				}
			}
		}
		((TextView) findViewById(R.id.tv_topbar_middle))
				.setText(mCurReviseJson.title);
		findViewById(R.id.tv_view_question).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// showQuestion();
						QuestionViewActivity.createInstance(
								ReviseActivity.this, mCurReviseJson.title);
					}

				});
		InitTextView();
		InitImage();
		InitViewPager();
		findViewById(R.id.btnSubmit).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(ReviseActivity.this).setTitle("提交批改")
						.setMessage("确定提交批改?").setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										if (IsSubmit == 1) {
											return;
										}
										IsSubmit = 1;
										DoSubmit();
									}
								}).setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {

									}
								}).show();

			}

		});
		/*
		 * findViewById(R.id.btnReject).setOnClickListener(new OnClickListener()
		 * {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub rejectRevise(); }
		 * 
		 * }); findViewById(R.id.btnQuestion).setOnClickListener( new
		 * OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub showQuestion(); }
		 * 
		 * });
		 */
		findViewById(R.id.btnMore).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popUpMyOverflow(v);
			}

		});
		// api.getTimu(mCurReviseJson.title, mHandler);
		// waitDialog = new WaitingDialog(this, "loading...");
		// Utils.showProgress(waitDialog, true);
		// 注册广播
		registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
				Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
	}

	public void popUpMyOverflow(View parentView) {
		int xOffset = (getXPx() - dip2px(150));
		int yOffset = dip2px(12);
		View popView = getLayoutInflater().inflate(R.layout.dialog_more, null);
		final PopupWindow popWind = new PopupWindow(popView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		popWind.setBackgroundDrawable(new BitmapDrawable(getResources(),
				(Bitmap) null));
		popWind.setOutsideTouchable(true); // 点击外部关闭。
		popWind.setAnimationStyle(android.R.style.Animation_Dialog); // 设置一个动画。
		popWind.showAsDropDown(parentView, xOffset, yOffset);
		popView.findViewById(R.id.tvReject).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) { // TODO Auto-generated method
						popWind.dismiss();
						rejectRevise();
					}

				});
		/*
		 * popView.findViewById(R.id.tvQuestion).setOnClickListener( new
		 * OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * popWind.dismiss(); showQuestion(); }
		 * 
		 * });
		 */
	}

	private void DoSubmit() {
		DoSaveAudio();
		try {
			if (mCurReviseJson == null
					|| mCurReviseJson.revise_reviser_points == null
					|| mCurReviseJson.revise_reviser_points.length == 0) {
				ToastShowMsg("批改内容不能为空");
				IsSubmit = 0;
				return;
			}

		} catch (Exception er) {
			ToastShowMsg("批改内容不能为空");
			IsSubmit = 0;
			return;
		}
		if (mCurReviseJson.delivery_score == 0
				|| mCurReviseJson.language_score == 0
				|| mCurReviseJson.topic_score == 0) {
			ToastShowMsg("请评分  ");
			IsSubmit = 0;
			return;
		}
		if (mCurReviseJson.overall_revise == null
				|| mCurReviseJson.overall_revise.length() == 0) {
			ToastShowMsg("请进行语音评价 ");
			IsSubmit = 0;
			return;
		}
		if (mCurReviseJson.suggestion_revise == null
				|| mCurReviseJson.suggestion_revise.length() == 0) {
			ToastShowMsg("请进行学习建议 ");
			IsSubmit = 0;
			return;
		}
		pd = ProgressDialog.show(ReviseActivity.this, "提交批改", "批改提交中，请稍后……");
		pd.show();
		api.submit(mCurReviseJson, mHandler);
	}

	private void DoSaveAudio() {
		try {
			((ReviseFragment) mPageAdapter.fragment.get(1)).generateAudio();
			((ReviseFragment) mPageAdapter.fragment.get(1)).getPointArray();
			doStopAudio();
		} catch (Exception er) {
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	/*
	 * 初始化标签名
	 */
	public void InitTextView() {
		view1 = (TextView) findViewById(R.id.tv_guid1);
		view2 = (TextView) findViewById(R.id.tv_guid2);
		view3 = (TextView) findViewById(R.id.tv_guid3);
		view1.setOnClickListener(new txListener(0));
		view2.setOnClickListener(new txListener(1));
		view3.setOnClickListener(new txListener(2));
	}

	public class txListener implements View.OnClickListener {
		private int index = 0;

		public txListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mPagerVp.setCurrentItem(index);
		}
	}

	/*
	 * 初始化图片的位移像素
	 */
	public void InitImage() {
		image = (ImageView) findViewById(R.id.cursor);
		bmpW = getXPx() / 3;
		LayoutParams lp = image.getLayoutParams();
		lp.height = 12;
		lp.width = bmpW;
		image.setLayoutParams(lp);
		image.setBackgroundColor(Color.argb(255, 106, 180, 159));
	}

	/*
	 * 初始化ViewPager
	 */
	public void InitViewPager() {
		mPagerVp = (BTViewPager) findViewById(R.id.vp_pager);
		mPageAdapter = new MyRevisePageAdapter(this, this
				.getSupportFragmentManager());
		mPagerVp.setAdapter(mPageAdapter);
		mPagerVp.setCurrentItem(0);// 设置当前显示标签页为第一页
		mPagerVp.setOnPageChangeListener(new MyOnPageChangeListener());// 页面变化时的监听器
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {
		private int one = bmpW;// 两个相邻页面的偏移量

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			Animation animation = new TranslateAnimation(currIndex * one, arg0
					* one, 0, 0);// 平移动画
			currIndex = arg0;
			animation.setFillAfter(true);// 动画终止时停留在最后一帧，不然会回到没有执行前的状态
			animation.setDuration(200);// 动画持续时间0.2秒
			image.startAnimation(animation);// 是用ImageView来显示动画的
			int i = currIndex + 1;
		}
	}

	@Override
	public void onMenuButtonClicked() {
		// TODO Auto-generated method stub

	}

	@Override
	public void OnMenuSelected(int position) {
		// TODO Auto-generated method stub

	}

	@Override
	public ReviseJson getReviseJson() {
		// TODO Auto-generated method stub
		return mCurReviseJson;
	}

	private void doStopAudio() {
		try {
			((RateFragment) mPageAdapter.fragment.get(0)).pauseAudio();
			((ReviseFragment) mPageAdapter.fragment.get(1)).pauseAudio();
		} catch (Exception er) {
		}
	}

	@Override
	public void doSave() {
		// TODO Auto-generated method stub
		Gson gson = new Gson();
		mCurReviseJson.end_at=ConvertUtils.getCurTime();
		rInfo.json = gson.toJson(mCurReviseJson);
		LocalRevise.doUpdateRevise(new DBUtil(this).sld, rInfo);
	}

	/*
	 * 显示答案
	 */
	private void showQuestion() {
		final AlertDialog qDialog = new AlertDialog.Builder(
				ReviseActivity.this, R.style.AlertDialog).create();
		qDialog.show();
		final Window window = qDialog.getWindow();
		window.setContentView(R.layout.dialog_question);
		android.view.WindowManager.LayoutParams lp = window.getAttributes();
		lp.width = getXPx() - 20;
		window.setAttributes(lp);
		window.findViewById(R.id.img_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						qDialog.dismiss();
					}
				});
		window.findViewById(R.id.btnCancel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						qDialog.dismiss();
					}
				});
		((TextView) window.findViewById(R.id.tvQuestion)).setText(Question);
	}

	/*
	 * 打回
	 */
	private void rejectRevise() {
		alertDialog = new AlertDialog.Builder(ReviseActivity.this,
				R.style.AlertDialog).create();
		alertDialog.show();
		final Window window = alertDialog.getWindow();
		window.setContentView(R.layout.dialog_reject);
		android.view.WindowManager.LayoutParams lp = window.getAttributes();
		lp.width = getXPx() - 20;
		window.setAttributes(lp);
		window.findViewById(R.id.img_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						alertDialog.dismiss();
					}
				});
		window.findViewById(R.id.btnCancel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						alertDialog.dismiss();
					}
				});

		window.findViewById(R.id.btnOk).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						String reason = ((EditText) window
								.findViewById(R.id.edt_reason)).getText()
								.toString();
						if (reason != null && reason.length() > 0) {
							api.reject(mCurReviseJson.xiaofei_id + "", reason,
									mHandler);
						}

					}
				});
		alertDialog.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
	}

	@Override
	protected void RecMsgFromHandler(Message msg) {
		// TODO Auto-generated method stub
		super.RecMsgFromHandler(msg);
		switch (msg.what) {
		case Constants.REVISE_REJECT:
			rejectResult(msg.obj);
			break;
		case Constants.REVISE_GETQUESTION:
			setQuestion(msg.obj);
			break;
		case Constants.REVISE_SUBMIT:
			IsSubmit = 0;
			submitResult(msg.obj);
			pd.dismiss();
			break;
		}
	}

	/*
	 * 提交返回结果
	 */
	private void submitResult(Object obj) {
		try {
			JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 0) {
				LocalRevise.doUpdateReviseStatus(new DBUtil(this).sld, mCurReviseJson.xiaofei_id, 1);
				finish();
				return;
			} else if (status == 404) {
				ToastShowMsg("消费记录异常");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ToastShowMsg("网络出问题了,请稍后在试...");
	}

	/*
	 * 打回返回结果
	 */
	private void rejectResult(Object obj) {
		try {
			JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 0) {
				alertDialog.dismiss();
				finish();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * 显示题目
	 */
	private void setQuestion(Object obj) {
		try {
			JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 0) {
				JSONObject json2 = JsonUtils
						.getJSONObject(json, "values", null);
				Question = JsonUtils.getString(json2, "timu");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		findViewById(R.id.lly_back).performClick();
	}

	/**
	 * 监听是否点击了home键将客户端推到后台
	 */
	private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
		String SYSTEM_REASON = "reason";
		String SYSTEM_HOME_KEY = "homekey";
		String SYSTEM_HOME_KEY_LONG = "recentapps";

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
				findViewById(R.id.lly_back).performClick();
			}
		}
	};

	@Override
	public void doStop(int pageIndex) {
		// TODO Auto-generated method stub
	if(pageIndex==0)
	{
		((ReviseFragment) mPageAdapter.fragment.get(1)).pauseAudio2();
	}else
	{
		((RateFragment) mPageAdapter.fragment.get(0)).pauseAudio2();
	}
	}
}
